package com.dms.modules.payment.service.impl;

import com.dms.common.exception.BusinessException;
import com.dms.modules.order.entity.Order;
import com.dms.modules.order.service.OrderService;
import com.dms.modules.payment.dto.PaymentDTO;
import com.dms.modules.payment.entity.AlipayOrder;
import com.dms.modules.payment.service.AlipayService;
import com.dms.modules.payment.service.PaymentService;
import com.dms.modules.cart.service.CartService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 支付服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {

    private final OrderService orderService;
    private final AlipayService alipayService;
    private final CartService cartService;
    // private final WechatPayService wechatPayService; // 微信支付服务，暂未实现

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createPayment(Long userId, PaymentDTO paymentDTO) {
        // 获取所有订单信息
        List<Order> orders = orderService.listByIds(paymentDTO.getOrderIds());
        
        // 验证订单数量
        if (orders.size() != paymentDTO.getOrderIds().size()) {
            throw new BusinessException("部分订单不存在");
        }
        
        // 验证订单所属用户和状态
        for (Order order : orders) {
            if (!order.getUserId().equals(userId)) {
                throw new BusinessException("无权访问订单：" + order.getOrderNo());
            }
            if (order.getStatus() != 0) { // 假设0是待支付状态
                throw new BusinessException("订单状态不正确：" + order.getOrderNo());
            }
        }

        // 计算总金额
        BigDecimal totalAmount = orders.stream()
            .map(Order::getTotalAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 生成订单号（如果是多个订单则合并）
        String orderNo;
        if (orders.size() > 1) {
            orderNo = orders.get(0).getOrderNo() + "_m" + orders.size();
        } else {
            orderNo = orders.get(0).getOrderNo();
        }

        // 更新所有订单的支付方式
        orders.forEach(order -> {
            order.setPaymentMethod(paymentDTO.getPaymentType());
            orderService.updateById(order);
        });

        // 根据支付方式创建支付订单
        switch (paymentDTO.getPaymentType().toLowerCase()) {
            case "alipay":
                return createAlipayPayment(orderNo, totalAmount, orders);
            case "wechat":
                return createWechatPayment(orderNo, totalAmount, orders);
            default:
                throw new BusinessException("不支持的支付方式：" + paymentDTO.getPaymentType());
        }
    }

    private String createAlipayPayment(String mergedOrderNo, BigDecimal totalAmount, List<Order> orders) {
        try {
            // 创建支付宝订单
            AlipayOrder alipayOrder = new AlipayOrder();
            alipayOrder.setOrderNo(mergedOrderNo);
            // 格式化金额为两位小数的字符串
            alipayOrder.setTotalAmount(String.format("%.2f", totalAmount));
            alipayOrder.setSubject("合并订单支付-" + mergedOrderNo);
            alipayOrder.setTradeStatus("WAIT_BUYER_PAY");
            alipayOrder.setUserId(orders.get(0).getUserId());

            // 保存支付宝订单到数据库
            alipayService.save(alipayOrder);
            log.info("保存支付宝订单成功: {}", alipayOrder);

            // 调用支付宝接口创建支付订单
            return alipayService.createPayment(alipayOrder);
        } catch (Exception e) {
            log.error("创建支付宝订单失败: mergedOrderNo={}, error={}", mergedOrderNo, e.getMessage(), e);
            throw new BusinessException("创建支付宝订单失败: " + e.getMessage());
        }
    }

    private String createWechatPayment(String mergedOrderNo, BigDecimal totalAmount, List<Order> orders) {
        // TODO: 实现微信支付
        throw new BusinessException("微信支付暂未实现");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handlePaymentCallback(String paymentType, String orderNo, String paymentNo, boolean success) {
        try {
            // 判断是否是合并支付订单
            if (orderNo.contains("_m")) {
                String baseOrderNo = orderNo.substring(0, orderNo.indexOf("_m"));
                // 获取原始订单
                Order firstOrder = orderService.lambdaQuery()
                    .eq(Order::getOrderNo, baseOrderNo)
                    .one();
                
                if (firstOrder == null) {
                    log.error("订单不存在：{}", baseOrderNo);
                    return false;
                }

                // 获取同一批次的所有订单
                List<Order> orders = orderService.lambdaQuery()
                    .eq(Order::getUserId, firstOrder.getUserId())
                    .eq(Order::getStatus, 0)
                    .eq(Order::getPaymentMethod, paymentType)
                    .le(Order::getCreateTime, firstOrder.getCreateTime())
                    .last("LIMIT " + orderNo.substring(orderNo.indexOf("m") + 1))
                    .list();

                if (success) {
                    // 批量更新订单状态为已支付
                    orders.forEach(order -> {
                        order.setStatus(1); // 假设1表示已支付状态
                        order.setPaymentNo(paymentNo);
                        order.setPaymentTime(java.time.LocalDateTime.now());
                        orderService.updateById(order);
                    });
                    return true;
                }
            } else {
                // 单个订单支付处理
                Order order = orderService.lambdaQuery()
                    .eq(Order::getOrderNo, orderNo)
                    .one();

                if (order == null) {
                    log.error("订单不存在：{}", orderNo);
                    return false;
                }

                if (success) {
                    order.setStatus(1);
                    order.setPaymentNo(paymentNo);
                    order.setPaymentTime(java.time.LocalDateTime.now());
                    orderService.updateById(order);
                    return true;
                }
            }

            return false;
        } catch (Exception e) {
            log.error("处理支付回调失败", e);
            return false;
        }
    }

    @Override
    public boolean queryPaymentStatus(Long userId, Long orderId) {
        Order order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在或无权访问");
        }
        return order.getStatus() == 1; // 假设1表示已支付状态
    }
} 